package utils;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;

/**
 * Title:字符工具类 Description:用于方便的获取或转换一些字符串值
 *
 * @author WangXuDong
 * @version 1.0
 */
public class CharUtil {
    private static final Logger log = LoggerFactory.getLogger(CharUtil.class);

    /**
     * 将String 转化成Integer 不能转化返回Null
     *
     * @param numStr
     * @return
     */
    public static Integer stringParsInt(String numStr) {
        Integer numint;
        if (CharUtil.isEmpty(numStr)) {
            numint = null;
        } else {
            try {
                if (numStr.indexOf(".") > 0) {
                    numStr = numStr.substring(0, numStr.indexOf("."));
                } else if (numStr.indexOf(".") == 0) {
                    numStr = "0";
                }
                numint = Integer.parseInt(numStr);
            } catch (NumberFormatException e) {
                log.warn(e.getMessage());
                numint = null;
            }
        }
        return numint;
    }

    /**
     * 将String 转成Long 不能转返回null
     *
     * @param numStr
     * @return
     */
    public static Long stringParsLong(String numStr) {
        Long num;
        if (CharUtil.isEmpty(numStr)) {
            num = null;
        } else {
            try {
                if (numStr.indexOf(".") > 0) {
                    numStr = numStr.substring(0, numStr.indexOf("."));
                } else if (numStr.indexOf(".") == 0) {
                    numStr = "0";
                }
                num = Long.parseLong(numStr);
            } catch (NumberFormatException e) {
                log.warn(e.getMessage());
                num = null;
            }
        }

        return num;
    }

    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    public static boolean ifLength(String str, int length) {
        return str != null && !str.trim().isEmpty() && str.length() == length;
    }

    /**
     * 获取一个字符串的实际长度，中文或中文符号每一个等于两个单位长度英文字母
     *
     * @param str
     * @return 一个字符串的实际长度
     */
    public static int stringLength(String str) {
        int length = 0;
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if ((arr[i] + "").getBytes().length == 1) {
                length += 1;
            } else {
                length += 2;
            }
        }
        return length;
    }


    /**
     * 获取随机字符串
     *
     * @param num
     * @return
     */
    public static String getRandomString(Integer num) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 从开始截取相应长度的字符串，长度为实际长度，一个中文或中文符号占两个单位的长度
     * 字符串长度大于0
     *
     * @param str       字符串
     * @param maxLength 截取的最大长度,一个中文或中文符号占两个单位的长度
     * @return 新字符串
     * @throws
     */
    public static String subStringByte(String str, int maxLength) {
        String nstr = "";
        if (str == null) {
            return null;
        }
        char[] arr = str.toCharArray();
        try {
            if (maxLength <= 0) {
                throw new Exception("字符串长度不能小于等于0,length:" + maxLength);
            }
            for (int i = 0; i < arr.length; i++) {
                if (maxLength > 0) {
                    if ((arr[i] + "").getBytes().length == 1) {
                        maxLength -= 1;
                    } else {
                        maxLength -= 2;
                    }
                    nstr += arr[i] + "";
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return nstr;

    }

    /**
     * 判断字符串是否是整数
     */
    public static boolean isInteger(String value) {
        try {
            Integer.parseInt(value);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 判断字符串是否是浮点数
     */
    public static boolean isDouble(String value) {
        try {
            Double.parseDouble(value);
            return value.contains(".");
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 获取一个指定长度的随机数
     *
     * @param length 长度
     * @return 随机数字符串
     */
    public static String getRanNumber(int length) {
        if (length <= 0) {
            length = 1;
        }
        String num = "";
        for (int i = 0; i < length; i++) {
            num += String.valueOf((int) (Math.random() * 10));
        }
        return num;
    }

    /**
     * 获取一个随机数在一定区域内包含 min 和 max
     *
     * @param min 最小数
     * @param max 最大数
     * @return 随机数
     */
    public static int getIntRanNumber(int min, int max) {
        if (min >= max) {
            return max;
        }
        int rannum = (int) (min + Math.random() * (max - min + 1));
        return rannum;
    }

    /**
     * 获取十六进制的颜色代码.例如 "#6E36B4" , For HTML ,
     *
     * @return String
     */
    public static String getRandColorCode() {
        String r, g, b;
        Random random = new Random();
        r = Integer.toHexString(random.nextInt(256)).toUpperCase();
        g = Integer.toHexString(random.nextInt(256)).toUpperCase();
        b = Integer.toHexString(random.nextInt(256)).toUpperCase();

        r = r.length() == 1 ? "0" + r : r;
        g = g.length() == 1 ? "0" + g : g;
        b = b.length() == 1 ? "0" + b : b;

        return r + g + b;
    }

    /**
     * 随机生成指定长度的小写字母和数组组成的字符串
     *
     * @param length    字符串长度
     * @param allLetter 是否全是字母
     * @return 生成的字符串
     */
    public static String getRanString(int length, boolean allLetter) {
        String[] strs = new String[]{"a", "b", "c", "d", "e", "f", "g", "h",
                "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
                "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9"};
        String retStr = "";
        if (allLetter) {
            Random random = new Random();
            for (int i = 0; i < length; i++) {
                int rad = random.nextInt(26);
                retStr += strs[rad];
            }
        } else {
            Random random = new Random();
            for (int i = 0; i < length; i++) {
                int rad = random.nextInt(36);
                retStr += strs[rad];
            }
        }
        return retStr;
    }

    /**
     * 取两个字符之间的字符，返回一个字符串数组
     *
     * @param strSrc 源字符串
     * @param from   开始字符
     * @param to     结束字符
     * @return
     */
    public static String[] getTokenString(String strSrc, String from, String to) {
        if (from == null || from.isEmpty()) {
            return null;
        }
        if (to == null || to.isEmpty()) {
            return null;
        }
        int nLast = strSrc.indexOf(from);
        if (nLast == -1) {
            return null;
        }
        int nNext;
        ArrayList<String> list = new ArrayList<String>();
        String str;
        while ((nNext = strSrc.indexOf(to, nLast + from.length())) != -1) {
            str = strSrc.substring(nLast + from.length(), nNext);
            list.add(str);
            nLast = nNext + to.length();
            nLast = strSrc.indexOf(from, nLast);
            if (nLast == -1) {
                break;
            }
        }
        if (list.size() == 0) {
            return null;
        }
        String[] s = new String[list.size()];
        list.toArray(s);

        return s;
    }

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }

    public static String formatCurrency(float val) {
        if (val == 0) {
            return "0.00";
        }
        DecimalFormat df = new DecimalFormat("0.00");

        return df.format(val);
    }

    public static String replacePLabel(String str) {
        return str.replace("<p>", "").replace("</p>", "");
    }


    public static String filterEmoji(String source) {
        if(StringUtils.isNotBlank(source)){
            return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "*");
        }else{
            return source;
        }
    }

    /**
     * @Description 将一段错误解码的字符串重新解码
     * @param str :     参数
     * @param formatFrom :  原来的格式
     * @param FormatTo :    改为的格式
     * @return java.lang.String
     * @Author dongxiangwei -- seven
     * @Date 2020/3/15 16:20
     */
    public static String convertEncodingFormat(String str, String formatFrom, String FormatTo) {
        String result = null;
        if (!(str == null || str.length() == 0)) {
            try {
                result = new String(str.getBytes(formatFrom), FormatTo);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
